package cn.edu.nju.software.cdiy.dao.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.edu.nju.software.cdiy.algorithm.performance.MainBoardEvaluator;
import cn.edu.nju.software.cdiy.bean.BRD_CPU;
import cn.edu.nju.software.cdiy.bean.BRD_MB;
import cn.edu.nju.software.cdiy.bean.Brand;
import cn.edu.nju.software.cdiy.bean.CPU;
import cn.edu.nju.software.cdiy.bean.Cha_MBArchitect;
import cn.edu.nju.software.cdiy.bean.Chassis;
import cn.edu.nju.software.cdiy.bean.Disk;
import cn.edu.nju.software.cdiy.bean.Graphics;
import cn.edu.nju.software.cdiy.bean.Hardware;
import cn.edu.nju.software.cdiy.bean.HardwareSet;
import cn.edu.nju.software.cdiy.bean.Interface;
import cn.edu.nju.software.cdiy.bean.MB_CPUXL;
import cn.edu.nju.software.cdiy.bean.MB_Interface;
import cn.edu.nju.software.cdiy.bean.MB_MemFrequency;
import cn.edu.nju.software.cdiy.bean.MainBoard;
import cn.edu.nju.software.cdiy.bean.Memory;
import cn.edu.nju.software.cdiy.bean.Value;
import cn.edu.nju.software.cdiy.dao.MainBoardDao;
import cn.edu.nju.software.cdiy.util.Changer;
import cn.edu.nju.software.cdiy.util.Constant;
import cn.edu.nju.software.cdiy.util.FilterItem;
import cn.edu.nju.software.cdiy.util.Item;
import cn.edu.nju.software.cdiy.util.NumberFormatter;
import cn.edu.nju.software.cdiy.util.Pager;
import cn.edu.nju.software.cdiy.util.SortByHotAsc;
import cn.edu.nju.software.cdiy.util.SortType;
import cn.edu.nju.software.cdiy.util.SortWay;


public class MainBoardDaoImpl implements MainBoardDao {
	
	@Autowired
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	// public void printModel(){
	// Session s = sessionFactory.getCurrentSession();
	// List list = s.createQuery("from MainBoard").list();
	// s.close();
	// MainBoard mb = (MainBoard) list.get(0);
	// System.out.println(mb.getModel());
	// }

	@Override
	public List<MainBoard> getMBList(int page, SortType s, HardwareSet hs,
			SortWay sw) {
		// System.out.println("进入getmblist");

		Session sess = sessionFactory.getCurrentSession();
		String sql = null;
		List<MainBoard> list = null;

		// 第page页的第minNum条记录到maxNum条记录 每次返回10页的内容
		int maxNum = Pager.getMax(page);
		int minNum = Pager.getMin(maxNum);

		// System.out.println("min:" + minNum + "..max:" + maxNum);
		switch (s) {
		case PRICE:
			if (sw == SortWay.ASC || sw == SortWay.DEFAULT)
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY OPRICE ASC";
			else
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY OPRICE DESC";
			list = sess.createQuery(sql).list();
			break;
		case PERFORMANCE:
			if (sw == SortWay.DESC || sw == SortWay.DEFAULT)
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY PERFORMANCE DESC";
			else
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY PERFORMANCE ASC";
			list = sess.createQuery(sql).list();
			break;
		case W_SCORE:
			if (sw == SortWay.DESC || sw == SortWay.DEFAULT)
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY WSCORE DESC";
			else
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY WSCORE ASC";
			list = sess.createQuery(sql).list();
			break;
		case Z_SCORE:
			if (sw == SortWay.DESC || sw == SortWay.DEFAULT)
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY ZSCORE DESC";
			else
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY ZSCORE ASC";
			list = sess.createQuery(sql).list();
			break;
		case NEW:
			if (sw == SortWay.DESC || sw == SortWay.DEFAULT)
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY INSTORAGETIME DESC";
			else
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY INSTORAGETIME ASC";
			list = sess.createQuery(sql).list();
			break;
		case HOT:
			sql = "FROM MainBoard WHERE STATE=882";
			list = sess.createQuery(sql).list();
			if (sw == SortWay.DESC || sw == SortWay.DEFAULT)
				Collections.sort(list);
			else {
				Collections.sort(list, new SortByHotAsc());
			}
			break;
		default:
			break;

		}
		// if (list != null)
		// System.out.println("getmblist 不空");
		list = filterList(hs, list, minNum, maxNum);
		
		return list;
	}

	private List<MainBoard> filterList(HardwareSet hs, List<MainBoard> list,
			int min, int max) {

		/*
		 * 分别由各部件的filter对待检测的部件表进行筛选 目前有2个 后期可以继续添加 CPU Memory
		 */
		// System.out.println("进入filterlist");
		// if (list != null)
		// System.out.println("filterlist 不空");
		list = uniFilter(hs, list);

		// 最终根据页数的要求返回list
		List<MainBoard> returnList = new Pager<MainBoard>().getPageList(list,min, max);

		return returnList;
	}

	public List<MainBoard> ChassisFilter(HardwareSet hs, List<MainBoard> l) {
		/*
		 * 机箱对主板的限制 主板板型
		 */
		if (hs.getChassis() != null) {
			// 获取机箱适用的主板板型
			Chassis Cha = hs.getChassis();
			Session sess = sessionFactory.getCurrentSession();
			int id = Cha.getId();
			String sql = "FROM Cha_MBArchitect WHERE Cha=:id";
			Query query = sess.createQuery(sql);
			query.setLong("id", id);
			List<Cha_MBArchitect> list = query.list();
			// 返回的List
			System.out.println(list.size());
			List<MainBoard> returnList = new ArrayList<MainBoard>();

			for (int i = 0; i < l.size(); i++) {
				// 遍历原表进行筛选
				MainBoard nowMB = l.get(i);
				int mbArchitect = nowMB.getMBArchitect().getKey();

				for (int j = 0; j < list.size(); j++) {
					// 检测这个主板的板型是否支持此Chassis
					if (list.get(j).getMbArchitect().getKey() == mbArchitect) {
						// 若支持这个系列 则加入返回list 并跳出进行下一个主板的检验
						returnList.add(nowMB);
					} else
						continue;
				}
			}
			
			return returnList;
		} else
			return l;
	}

	private List<MainBoard> DiskFilter(HardwareSet hs, List<MainBoard> l) {

		/*
		 * 硬盘对主板的限制 硬盘SATA接口标准
		 */
		if (hs.getDisk() != null) {
			// 获取硬盘的SATA接口
			Disk Disk = hs.getDisk();
			int intfStd = Disk.getIntfStd().getId();
			Session sess = sessionFactory.getCurrentSession();
			// 返回的List
			List<MainBoard> returnList = new ArrayList<MainBoard>();

			for (int i = 0; i < l.size(); i++) {
				// 遍历原表进行筛选
				MainBoard nowMB = l.get(i);
				int id = nowMB.getId();

				String sql = "FROM MB_Interface WHERE MB=" + id;
				List<MB_Interface> list = sess.createQuery(sql).list();

				for (int j = 0; j < list.size(); j++) {
					// 检测此是主板支持的SATA接口标准是否适合硬盘的SATA接口
					int SATA_id = list.get(j).getIntf_id().getId();
					if (SATA_id >= 34 && SATA_id <= 36) {
						if (SATA_id <= intfStd) {
							// 若支持这个系列 则加入返回list 并跳出进行下一个主板的检验
							returnList.add(nowMB);
							break;
						}
					} else
						continue;
				}
			}
			
			return returnList;
		} else
			return l;
	}

	private List<MainBoard> GraphicsFilter(HardwareSet hs, List<MainBoard> l) {

		/*
		 * 显卡对主板的限制 显卡总线接口标准
		 */
		if (hs.getGraphics() != null) {
			// 获取显卡的总线接口
			Graphics Gra = hs.getGraphics();
			int busINTF = Gra.getBUSIntf().getId();
			Session sess = sessionFactory.getCurrentSession();
			// 返回的List
			List<MainBoard> returnList = new ArrayList<MainBoard>();

			for (int i = 0; i < l.size(); i++) {
				// 遍历原表进行筛选
				MainBoard nowMB = l.get(i);
				int id = nowMB.getId();

				String sql = "FROM MB_Interface WHERE MB=" + id;
				List<MB_Interface> list = sess.createQuery(sql).list();

				for (int j = 0; j < list.size(); j++) {
					// 检测此是主板支持的显卡接口标准是否适合显卡的总线接口
					int BI_id = list.get(j).getIntf_id().getId();
					if (BI_id >= 16 && BI_id <= 27) {
						if (BI_id >= busINTF) {
							// 若支持这个系列 则加入返回list 并跳出进行下一个主板的检验
							returnList.add(nowMB);
							break;
						}
					} else
						continue;
				}
			}
			
			return returnList;
		} else
			return l;
	}

	// public void testOneToMany() {
	// Session sess = sessionFactory.getCurrentSession();
	// String sql = "FROM MainBoard WHERE ID=1";
	// List<MainBoard> list = sess.createQuery(sql).list();
	// MainBoard mb = list.get(0);
	// Set<Value> cpuxlSet = mb.getCpuxlSet();
	// for(Value v:cpuxlSet){
	// System.out.println(v.getKey()+" "+v.getValue());
	// }
	// 
	// }
	
	private List<MainBoard> CPUFilter(HardwareSet hs, List<MainBoard> l) {
		/*
		 * cpu对主板的限制 cpu系列 cpumanu
		 */
		if (hs.getCpu() != null) {
			// 获取cpuxl
			CPU cpu = hs.getCpu();
			int cpuxl = cpu.getCPUXL().getKey();
			int cpuBrand = cpu.getBrand().getId();
			// 返回的list
			List<MainBoard> returnList = new ArrayList<MainBoard>();

			for (int i = 0; i < l.size(); i++) {
				// 遍历原表进行筛选
				// 先判断CPU生产商是否符合
				if(l.get(i).getCPUManu().getId() == cpuBrand){
					//判断CPU系列是否符合
					MainBoard nowMB = l.get(i);
					Set<MB_CPUXL> s = nowMB.getCpuxlSet();
					for(MB_CPUXL m:s){
						if(m.getCpuxl().getKey() == cpuxl ){
							// 若支持这个系列 则加入返回list 并跳出进行下一个mb的检验
							returnList.add(nowMB);
							break;
						}else
							continue;
					}
				}
			}
			return returnList;
		} else
			return l;
	}
	

	private List<MainBoard> MemoryFilter(HardwareSet hs, List<MainBoard> l) {
		/*
		 * 内存对主板的限制 内存容量 内存频率 内存类型
		 */
		if (hs.getMemory() != null) {
			Memory mem = hs.getMemory();
			// 主板内存容量值要大于此值
			double memCapacity = NumberFormatter.getNumber(mem.getMemCapacity()
					.getValue());
			// 主板内存频率要小于此值
			int memFrequency = mem.getMemFrequency().getKey();
			// 主板内存支持类型要等于此值
			int memType = mem.getMemType().getKey();

			Session sess = sessionFactory.getCurrentSession();
			// 返回的list
			List<MainBoard> returnList = new ArrayList<MainBoard>();

			for (int i = 0; i < l.size(); i++) {
				// 遍历原表进行筛选
				MainBoard nowMB = l.get(i);

				// 对最大内存进行检查
				double maxMem = NumberFormatter.getNumber(nowMB.getMaxMem()
						.getValue());
				if (maxMem < memCapacity)
					continue;
				// 对内存类型进行检查
				if (nowMB.getCompatibleMEM().getKey() != memType)
					continue;

				// 对内存频率进行检查
				int id = nowMB.getId();
				String sql = "FROM MB_MemFrequency WHERE MB=" + id;
				List<MB_MemFrequency> list = sess.createQuery(sql).list();

				for (int j = 0; j < list.size(); j++) {
					// 检测此MainBoard的最大内存容量和内存频率是否符合要求
					if (list.get(j).getMemFrequency().getKey() <= memFrequency) {
						// 若符合要求则加入返回list 并跳出进行下一个mb的检验
						returnList.add(nowMB);
						break;
					} else
						continue;

				}
			}
			
			return returnList;
		} else
			return l;
	}

	@Override
	public List<Hardware> getNewestList() {

		Session sess = sessionFactory.getCurrentSession();
		String sql = "FROM MainBoard WHERE STATE=882 ORDER BY INSTORAGETIME DESC";
		List<MainBoard> list = sess.createQuery(sql).list();
		if (list.size() > Constant.NEW_LIST_LENGTH)
			list = list.subList(0, Constant.NEW_LIST_LENGTH);
		List<Hardware> returnList = Changer.toHardwareList(list);
		
		return returnList;
	}

	public List<MainBoard> getList() {
		Session sess = sessionFactory.getCurrentSession();
		String sql = "FROM MainBoard WHERE STATE=882 ORDER BY INSTORAGETIME DESC";
		List<MainBoard> list = sess.createQuery(sql).list();

		
		return list;
	}

	@Override
	public List<Hardware> getHottestList() {

		Session sess = sessionFactory.getCurrentSession();
		String sql = "FROM MainBoard WHERE STATE=882";
		List<MainBoard> list = sess.createQuery(sql).list();

		Collections.sort(list);

		// list=list.subList(0, Constant.hotNum-1);
		if (list.size() > Constant.HOT_LIST_LENGTH)
			list = list.subList(0, Constant.HOT_LIST_LENGTH);

		List<Hardware> returnList = Changer.toHardwareList(list);
		
		return returnList;
	}

	@Override
	public List<Brand> getBrandList() {

		// System.out.println("daoimpl getBrandList");
		Session sess = sessionFactory.getCurrentSession();
		String sql = "FROM BRD_MB";
		List<Brand> returnList = new ArrayList<Brand>();

		List<BRD_MB> list = sess.createQuery(sql).list();

		for (int i = 0; i < list.size(); i++) {
			returnList.add(list.get(i));
			// System.out.println(returnList.get(i));
		}

		// System.out.println("daoimpl getBrandList return");
		
		return returnList;
	}

	@Override
	public List<MainBoard> filter(int page, Map<String, List<Integer>> map,
			SortType st, SortWay sw, HardwareSet hs) {

		// if (map != null)
		// System.out.println("filter map不空");
		// 搜索时的过滤方法
		if (map==null || map.size()==0) {
			// System.out.println("filterlist map为空");
			return getMBList(page, st, hs, sw);
		}

		// 获得此产品表
		List<MainBoard> hwList = getFilterList(hs, st, sw);
//		System.out.println("hwList size:" + hwList.size()
//				+ "===================================");
		// 最后的匹配表
		List<MainBoard> matchList = new ArrayList<MainBoard>();

		// 开始过滤
		Set<String> keys = map.keySet();

		int i = 0;
		for (String s : keys) {
			i++;
			if (s.equals(Constant.mbItemNameList[0])) {
				// 品牌过滤
				List<Integer> list = map.get(s);
				for (int j = 0; j < hwList.size(); j++) {
					for (int k = 0; k < list.size(); k++) {
						if (hwList.get(j).getBrand().getBrand()
								.equals(getBrandById(list.get(k)).getBrand())) {
							matchList.add(hwList.get(j));
							break;
						}
					}
				}
			} else if (s.equals(Constant.mbItemNameList[1])) {
				List<Integer> list = map.get(s);

				for (int j = 0; j < hwList.size(); j++) {
					for (int k = 0; k < list.size(); k++) {
						if (Changer.checkPrice(hwList.get(j),
								Constant.MAINBOARD_PRICE[list.get(k) - 1]
										.getName())) {
							matchList.add(hwList.get(j));
							break;
						}
					}
				}

			} else if (s.equals(Constant.mbItemNameList[2])) {
				List<Integer> list = map.get(s);

				for (int j = 0; j < hwList.size(); j++) {
					for (int k = 0; k < list.size(); k++) {
						if (hwList.get(j).getMBArchitect().getValue()
								.equals(getValueByID(list.get(k)).getValue())) {
							matchList.add(hwList.get(j));
							break;
						}
					}
				}

			} else if (s.equals(Constant.mbItemNameList[3])) {
				List<Integer> list = map.get(s);

				for (int j = 0; j < hwList.size(); j++) {
					for (int k = 0; k < list.size(); k++) {
						if (hwList
								.get(j)
								.getCPUSlot()
								.getName()
								.equals(getInterfaceByID(list.get(k)).getName())) {
							matchList.add(hwList.get(j));
							break;
						}
					}
				}

			} else if (s.equals(Constant.mbItemNameList[4])) {
				List<Integer> list = map.get(s);

				for (int j = 0; j < hwList.size(); j++) {
					for (int k = 0; k < list.size(); k++) {
						if (hwList.get(j).getMaxMem().getValue()
								.equals(getValueByID(list.get(k)).getValue())) {
							matchList.add(hwList.get(j));
							break;
						}
					}
				}

			}
			if (i != keys.size()) {
				hwList = matchList;
				matchList = new ArrayList<MainBoard>();
			}
		}
		int maxNum = Pager.getMax(page);
		int minNum = Pager.getMin(maxNum);
		matchList = new Pager<MainBoard>().getPageList(matchList, minNum,
				maxNum);
		return matchList;
	}

	private List<MainBoard> getFilterList(HardwareSet hs, SortType st,
			SortWay sw) {

		/*
		 * 获取用于筛选的硬件列表 此列表可以由action提供 或由本方法从数据库获取
		 */
		List<MainBoard> l = new ArrayList<MainBoard>();
		Session sess = sessionFactory.getCurrentSession();
		String sql = null;

		switch (st) {
		case PRICE:

			if (sw == SortWay.ASC || sw == SortWay.DEFAULT)
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY OPRICE ASC";
			else
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY OPRICE DESC";
			l = sess.createQuery(sql).list();

			break;
		case W_SCORE:

			if (sw == SortWay.DESC || sw == SortWay.DEFAULT)
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY WSCORE DESC";
			else
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY WSCORE ASC";
			l = sess.createQuery(sql).list();

			break;
		case Z_SCORE:

			if (sw == SortWay.DESC || sw == SortWay.DEFAULT)
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY ZSCORE DESC";
			else
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY ZSCORE ASC";
			l = sess.createQuery(sql).list();

			break;
		case NEW:

			if (sw == SortWay.DESC || sw == SortWay.DEFAULT)
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY INSTORAGETIME DESC";
			else
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY INSTORAGETIME ASC";
			l = sess.createQuery(sql).list();

			break;
		case HOT:
			sql = "FROM MainBoard WHERE STATE=882";
			l = sess.createQuery(sql).list();
			if (sw == SortWay.DESC || sw == SortWay.DEFAULT)
				Collections.sort(l);
			else {
				Collections.sort(l, new SortByHotAsc());
			}
			break;
		case PERFORMANCE:
			if (sw == SortWay.DESC || sw == SortWay.DEFAULT)
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY PERFORMANCE DESC";
			else
				sql = "FROM MainBoard WHERE STATE=882 ORDER BY PERFORMANCE ASC";
			l = sess.createQuery(sql).list();
			break;
		default:
			break;

		}
		l = uniFilter(hs, l);
		
		return l;
	}

	@Override
	public List<MainBoard> search(String keywords, int page) {

		Session sess = sessionFactory.getCurrentSession();

		int maxNum = Pager.getMax(page);
		int minNum = Pager.getMin(maxNum);

		String sql = "FROM MainBoard";
		String keys[] = keywords.split(" ");
		for (int i = 0; i < keys.length; i++) {
			if (i == 0) {
				sql = sql + " WHERE MODEL LIKE '%" + keys[i] + "%'";
			} else {
				sql = sql + " OR MODEL LIKE '%" + keys[i] + "%'";
			}
		}
		List<MainBoard> list = sess.createQuery(sql).list();

		List<MainBoard> returnList = new Pager<MainBoard>().getPageList(list,
				minNum, maxNum);

		
		return returnList;
	}

	@Override
	public HashMap<String, List<Item>> getFilterBoard() {

		HashMap<String, List<Item>> map = new HashMap<String, List<Item>>();
		map.put(getBrandItem().getItemName(), getFilterBrandItem());
		map.put(getPriceItem().getItemName(), getFilterPriceItem());

		for (int i = 2; i < Constant.mbItemNameList.length; i++) {
			map.put(Constant.mbItemNameList[i], getFilterItemByNum(i));
		}

		return map;
	}

	private List<Item> getFilterItemByNum(int i) {

		Session sess = sessionFactory.getCurrentSession();
		FilterItem fi = new FilterItem();
		// itemName
		fi.setItemName(Constant.mbItemNameList[i]);

		String sql = null;
		List<Value> values = null;
		List<Item> choices = null;

		switch (i) {
		case 2:
			// 主板板型

			// itemChoiceList
			choices = new ArrayList<Item>();

			sql = "FROM Value WHERE KEY>=81 AND KEY<=90 ORDER BY VALUE";
			values = sess.createQuery(sql).list();

			for (int j = 0; j < values.size(); j++) {
				choices.add(new Item(values.get(j).getValue(), values.get(j)
						.getKey()));
			}

			break;
		case 3:
			// CPU插槽

			// itemChoiceList
			choices = new ArrayList<Item>();

			sql = "FROM Interface WHERE RE_MB=1 AND RE_CPU=1 ORDER BY INTF_TYPE,NAME";
			List<Interface> intfs = null;
			intfs = sess.createQuery(sql).list();

			for (int j = 0; j < intfs.size(); j++) {
				choices.add(new Item(intfs.get(j).getName(), intfs.get(j)
						.getId()));
			}

			break;
		case 4:
			// 最大内存

			// itemChoiceList
			choices = new ArrayList<Item>();

			sql = "FROM Value WHERE KEY>=91 AND KEY<=100 ORDER BY VALUE";
			values = sess.createQuery(sql).list();

			for (int j = 0; j < values.size(); j++) {
				choices.add(new Item(values.get(j).getValue(), values.get(j)
						.getKey()));
			}

			break;
		default:
			break;

		}
		
		return choices;
	}

	private FilterItem getItemByNum(int i) {

		Session sess = sessionFactory.getCurrentSession();
		FilterItem fi = new FilterItem();
		// itemName
		fi.setItemName(Constant.mbItemNameList[i]);

		String sql = null;
		List<Value> values = null;
		List<String> choices = null;

		switch (i) {
		case 2:
			// 主板板型

			// itemChoiceList
			choices = new ArrayList<String>();

			sql = "FROM Value WHERE KEY>=81 AND KEY<=90 ORDER BY VALUE";
			values = sess.createQuery(sql).list();

			for (int j = 0; j < values.size(); j++) {
				choices.add(values.get(j).getValue());
			}

			break;
		case 3:
			// CPU插槽

			// itemChoiceList
			choices = new ArrayList<String>();

			sql = "FROM Interface WHERE RE_MB=1 AND RE_CPU=1 ORDER BY INTF_TYPE,NAME";
			List<Interface> intfs = null;
			intfs = sess.createQuery(sql).list();

			for (int j = 0; j < intfs.size(); j++) {
				choices.add(intfs.get(j).getName());
			}

			break;
		case 4:
			// 最大内存

			// itemChoiceList
			choices = new ArrayList<String>();

			sql = "FROM Value WHERE KEY>=91 AND KEY<=100 ORDER BY VALUE";
			values = sess.createQuery(sql).list();

			for (int j = 0; j < values.size(); j++) {
				choices.add(values.get(j).getValue());
			}

			break;
		default:
			break;

		}
		fi.setItemChoiceList(choices);
		
		return fi;
	}

	private FilterItem getPriceItem() {

		// 价格项
		FilterItem fi = new FilterItem();
		fi.setItemName(Constant.mbItemNameList[1]);

		List<String> choices = new ArrayList<String>();
		for (int i = 0; i < (Constant.MAINBOARD_PRICE.length); i++) {
			choices.add(Constant.MAINBOARD_PRICE[i].getName());
		}

		fi.setItemChoiceList(choices);

		return fi;
	}

	private FilterItem getBrandItem() {

		Session sess = sessionFactory.getCurrentSession();
		FilterItem fi = new FilterItem();
		fi.setItemName(Constant.mbItemNameList[0]);

		String sql = "FROM BRD_MB";
		List<BRD_MB> brandList = sess.createQuery(sql).list();
		List<String> choices = new ArrayList<String>();

		for (int i = 0; i < brandList.size(); i++) {
			choices.add(brandList.get(i).getBrand());
		}

		fi.setItemChoiceList(choices);
		
		return fi;
	}

	@Override
	public MainBoard getOneById(int id) {

		Session sess = sessionFactory.getCurrentSession();
		MainBoard c = (MainBoard) sess.load(MainBoard.class, id);
		
		return c;
	}

	@Override
	public Map<String, List<String>> getInsertboard() {

		// 返回的map
		Map<String, List<String>> rMap = new HashMap<String, List<String>>();

		Session sess = sessionFactory.getCurrentSession();
		String sql = null;
		List<String> l = null;
		List<Value> valueList = null;

		// 品牌
		sql = "FROM BRD_MB";
		l = new ArrayList<String>();
		List<BRD_MB> brandList = sess.createQuery(sql).list();
		for (int i = 0; i < brandList.size(); i++) {
			l.add(brandList.get(i).getBrand());
		}
		rMap.put(Constant.mbSelectStr[0], l);

		// CPU生产厂商
		sql = "FROM BRD_CPU";
		l = new ArrayList<String>();
		List<BRD_CPU> brandList1 = sess.createQuery(sql).list();
		for (int i = 0; i < brandList1.size(); i++) {
			l.add(brandList1.get(i).getBrand());
		}
		rMap.put(Constant.mbSelectStr[1], l);

		// 主板板型
		l = getValueByKey(81, 90);
		rMap.put(Constant.mbSelectStr[4], l);

		// CPU插槽
		l = new ArrayList<String>();
		sql = "FROM Interface WHERE RE_MB=1 AND RE_CPU=1 ORDER BY INTF_TYPE,NAME";
		List<Interface> cpuslist = sess.createQuery(sql).list();
		for (int i = 0; i < cpuslist.size(); i++) {
			l.add(cpuslist.get(i).getName());
		}
		rMap.put(Constant.mbSelectStr[8], l);

		// 最大支持内存
		l = getValueByKey(91, 100);
		rMap.put(Constant.mbSelectStr[5], l);

		// 芯片组
		l = getValueByKey(1, 80);
		rMap.put(Constant.mbSelectStr[2], l);

		// 适用内存类型
		l = getValueByKey(231, 235);
		rMap.put(Constant.mbSelectStr[3], l);

		// 支持通道
		l = getValueByKey(101, 105);
		rMap.put(Constant.mbSelectStr[6], l);

		// 电源接口
		l = new ArrayList<String>();
		sql = "FROM Interface WHERE RE_MB=1 AND RE_POW=1 ORDER BY INTF_TYPE,NAME";
		List<Interface> list = sess.createQuery(sql).list();
		for (int i = 0; i < list.size(); i++) {
			l.add(list.get(i).getName());
		}
		rMap.put(Constant.mbSelectStr[7], l);

		// 内存插槽
		l = new ArrayList<String>();
		sql = "FROM Interface WHERE RE_MEM=1 AND RE_MB=1 ORDER BY INTF_TYPE,NAME";
		List<Interface> list1 = sess.createQuery(sql).list();
		for (int i = 0; i < list1.size(); i++) {
			l.add(list1.get(i).getName());
		}
		rMap.put(Constant.mbSelectStr[9], l);

		// 一对多
		// CPU系列
		l = new ArrayList<String>();
		sql = "FROM Value WHERE KEY>=106 AND KEY<=160 ORDER BY VALUE";
		List<Value> list2 = sess.createQuery(sql).list();
		for (int i = 0; i < list2.size(); i++) {
			l.add(list2.get(i).getValue());
		}
		rMap.put(Constant.mbComboBoxStr[0], l);

		// 主板接口
		// 需要携带数量
		// 最终返回的map的list形如:
		// 3-SATA 3.0(即3个SATA 3.0接口)
		// l = new ArrayList<String>();
		// sql = "FROM Interface WHERE RE_MB=1 ORDER BY INTF_TYPE,NAME";
		// List<Interface> list3 = sess.createQuery(sql).list();
		// for (int i = 0; i < list3.size(); i++) {
		// l.add(list3.get(i).getIntf_type().getKey()+"@"+list3.get(i).getName());
		// }
		// rMap.put(Constant.mbComboBoxStr[1], l);
		// 扩展插槽
		l = new ArrayList<String>();
		sql = "FROM Interface WHERE INTF_TYPE=1055 ORDER BY INTF_TYPE,NAME";
		List<Interface> list3 = sess.createQuery(sql).list();
		for (int i = 0; i < list3.size(); i++) {
			l.add(list3.get(i).getName());
		}
		rMap.put(Constant.mbComboBoxStr[1], l);

		// I/O接口
		l = new ArrayList<String>();
		sql = "FROM Interface WHERE INTF_TYPE=1056 ORDER BY INTF_TYPE,NAME";
		List<Interface> list4 = sess.createQuery(sql).list();
		for (int i = 0; i < list4.size(); i++) {
			l.add(list4.get(i).getName());
		}
		rMap.put(Constant.mbComboBoxStr[2], l);

		// 支持内存频率
		l = new ArrayList<String>();
		sql = "FROM Value WHERE KEY>=236 AND KEY<=265 ORDER BY VALUE";
		List<Value> list5 = sess.createQuery(sql).list();
		for (int i = 0; i < list5.size(); i++) {
			l.add(list5.get(i).getValue());
		}
		rMap.put(Constant.mbComboBoxStr[3], l);

		
		return rMap;
	}

	@Override
	public boolean insertHardware(Map<String, List<String>> map) {
		try {
			// TODO Auto-generated method stub
			Session sess = sessionFactory.getCurrentSession();
			
			MainBoard mbd = new MainBoard();
			// 本方法处理外键和专属属性，通用属性由其他方法提供
			// mainboard有一对多的情况
			Iterator i = map.keySet().iterator();
			// 一对多的list
			List<String> mbCPUXL = null;
			// List<String> mbIntf = null;
			List<String> extendSlot = null;
			List<String> ioIntf = null;

			List<String> mbMemf = null;
			while (i.hasNext()) {
				String key = i.next().toString();
				List<String> list = map.get(key);
				String sql = null;
				if (key.equals(Constant.mbInforStr[0])) {
					mbd.setModel(list.get(0));
					// 外键
				} else if (key.equals(Constant.mbSelectStr[0])) {
					sql = "FROM BRD_MB WHERE BRAND='" + list.get(0) + "'";
					List<BRD_MB> bl = sess.createQuery(sql).list();
					mbd.setBrand(bl.get(0));
				} else if (key.equals(Constant.mbSelectStr[1])) {
					sql = "FROM BRD_CPU WHERE BRAND='" + list.get(0) + "'";
					List<BRD_CPU> bl = sess.createQuery(sql).list();
					mbd.setCPUManu(bl.get(0));
				} else if (key.equals(Constant.mbSelectStr[2])) {
					mbd.setChipSet(getValueByName(list.get(0)));
				} else if (key.equals(Constant.mbSelectStr[3])) {
					mbd.setCompatibleMEM(getValueByName(list.get(0)));
				} else if (key.equals(Constant.mbSelectStr[4])) {
					mbd.setMBArchitect(getValueByName(list.get(0)));
				} else if (key.equals(Constant.mbSelectStr[5])) {
					mbd.setMaxMem(getValueByName(list.get(0)));
				} else if (key.equals(Constant.mbSelectStr[6])) {
					mbd.setCompatibleTunnel(getValueByName(list.get(0)));
				} else if (key.equals(Constant.mbSelectStr[7])) {
					mbd.setPowerInterface(getInterfaceByName(list.get(0)));
				} else if (key.equals(Constant.mbSelectStr[8])) {
					mbd.setCPUSlot(getInterfaceByName(list.get(0)));
				} else if (key.equals(Constant.mbSelectStr[9])) {
					mbd.setMemSlot(getInterfaceByName(list.get(0)));
				} else if (key.equals(Constant.mbInforStr[1])) {
					// 非外键
					mbd.setSpecialFeature(list.get(0));
				} else if (key.equals(Constant.mbInforStr[2])) {
					mbd.setMemSlotNum(Integer.parseInt(list.get(0)));
				} else if (key.equals(Constant.mbInforStr[3])) {
					mbd.setSizeOfMB(list.get(0));
				} else if (key.equals(Constant.mbInforStr[4])) {
					mbd.setAttachment(list.get(0));
				} else if (key.equals(Constant.mbInforStr[5])) {
					mbd.setSoundCard(list.get(0));
				} else if (key.equals(Constant.mbInforStr[6])) {
					mbd.setNetworkAdapter(list.get(0));
				} else if (key.equals(Constant.mbInforStr[7])) {
					mbd.setRAID(list.get(0));
				} else if (key.equals(Constant.mbInforStr[8])) {
					mbd.setPowerMode(list.get(0));
				} else if (key.equals(Constant.mbComboBoxStr[0])) {
					// 一对多
					mbCPUXL = list;
				} else if (key.equals(Constant.mbComboBoxStr[1])) {
					extendSlot = list;
				} else if (key.equals(Constant.mbComboBoxStr[2])) {
					ioIntf = list;
				} else if (key.equals(Constant.mbComboBoxStr[3])) {
					mbMemf = list;
				} else {
					// 通用属性
					Changer.setUniAttribute(mbd, key, list);
				}

			}
			// 默认属性
			Changer.setDefaultAttribute(mbd);
			mbd.setState(getValueByID(Constant.HW_DEFAULT_STATE));

			mbd.setPerformance(new MainBoardEvaluator().getPerformance(mbd));

			
			sess.save(mbd);

			// CPU系列表MB_CPUXL
			for (int j = 0; j < mbCPUXL.size(); j++) {
				String s = mbCPUXL.get(j);
				Value cpuxl = getValueByName(s);
				MB_CPUXL mbcxl = new MB_CPUXL();

				mbcxl.setMb(mbd);
				mbcxl.setCpuxl(cpuxl);
				sess.save(mbcxl);
			}

			// 主板接口表MB_Interface
			for (int j = 0; j < extendSlot.size(); j++) {
				String s = extendSlot.get(j);
				int index = s.indexOf("@");
				int num = Integer.parseInt(s.substring(index + 1));
				Interface intf = getInterfaceByName(s.substring(0, index));

				MB_Interface mbi = new MB_Interface();
				mbi.setMb(mbd);
				mbi.setIntf_id(intf);
				mbi.setNum(num);
				sess.save(mbi);
			}
			for (int j = 0; j < ioIntf.size(); j++) {
				String s = ioIntf.get(j);
				int index = s.indexOf("@");
				int num = Integer.parseInt(s.substring(index + 1));
				Interface intf = getInterfaceByName(s.substring(0, index));

				MB_Interface mbi = new MB_Interface();
				mbi.setMb(mbd);
				mbi.setIntf_id(intf);
				mbi.setNum(num);
				sess.save(mbi);
			}

			// 内存频率表MB_MemFrequency
			for (int j = 0; j < mbMemf.size(); j++) {
				String s = mbMemf.get(j);
				Value v = getValueByName(s);

				MB_MemFrequency mbmf = new MB_MemFrequency();
				mbmf.setMb(mbd);
				mbmf.setMemFrequency(v);
				sess.save(mbmf);
			}
			//sess.flush();
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
		return true;
	}

	private List<String> getValueByKey(int i, int j) {

		List<String> rl = new ArrayList<String>();
		Session sess = sessionFactory.getCurrentSession();
		String sql = "FROM Value where KEY>=" + i + " AND KEY<=" + j
				+ " ORDER BY VALUE";
		List<Value> l = sess.createQuery(sql).list();
		for (int k = 0; k < l.size(); k++) {
			rl.add(l.get(k).getValue());
		}
		
		return rl;
	}

	private Value getValueByName(String name) {
		Session sess = sessionFactory.getCurrentSession();
		String sql = "FROM Value WHERE VALUE='" + name + "'";
		List<Value> l = sess.createQuery(sql).list();
		
		return l.get(0);

	}

	private Interface getInterfaceByName(String name) {
		Session sess = sessionFactory.getCurrentSession();
		String sql = "FROM Interface WHERE NAME='" + name + "'";
		List<Interface> l = sess.createQuery(sql).list();
		
		if (l.size() == 0)
			System.out.println(name + "接口未找到");
		return l.get(0);

	}

	private List<Item> getFilterPriceItem() {

		List<Item> choices = new ArrayList<Item>();
		for (int i = 0; i < (Constant.MAINBOARD_PRICE.length); i++) {
			choices.add(Constant.MAINBOARD_PRICE[i]);
		}
		return choices;
	}

	private List<Item> getFilterBrandItem() {

		Session sess = sessionFactory.getCurrentSession();

		String sql = "FROM BRD_MB";
		List<BRD_MB> brandList = sess.createQuery(sql).list();
		List<Item> choices = new ArrayList<Item>();

		for (int i = 0; i < brandList.size(); i++) {
			choices.add(new Item(brandList.get(i).getBrand(), brandList.get(i)
					.getId()));
		}

		
		return choices;
	}

	private Value getValueByID(Integer integer) {

		Session sess = sessionFactory.getCurrentSession();
		Value c = (Value) sess.load(Value.class, integer);
		
		return c;
	}

	private Interface getInterfaceByID(int id) {
		Session sess = sessionFactory.getCurrentSession();
		Interface c = (Interface) sess.load(Interface.class, id);
		
		return c;

	}

	private BRD_MB getBrandById(Integer integer) {

		Session sess = sessionFactory.getCurrentSession();
		BRD_MB c = (BRD_MB) sess.load(BRD_MB.class, integer);
		
		return c;
	}

	@Override
	public void save(MainBoard t) {

//		System.out.println("进入mb save");
		Session sess = sessionFactory.getCurrentSession();
		
		sess.saveOrUpdate(t);
		
		sess.flush();
//		System.out.println("退出mb save");
		
	}

	@Override
	public int filterPageNum(Map<String, List<Integer>> map, HardwareSet hs) {


		List<MainBoard> hwList = null;
		List<MainBoard> matchList = new ArrayList<MainBoard>();

		String sql = "FROM MainBoard WHERE STATE=882";
		Session sess = sessionFactory.getCurrentSession();
		hwList = sess.createQuery(sql).list();

		hwList = uniFilter(hs, hwList);

		if (map==null || map.size()==0)
			return hwList.size();
		// 开始过滤
		Set<String> keys = map.keySet();

		int i = 0;
		for (String s : keys) {
			i++;
			if (s.equals(Constant.mbItemNameList[0])) {
				// 品牌过滤
				List<Integer> list = map.get(s);
				for (int j = 0; j < hwList.size(); j++) {
					for (int k = 0; k < list.size(); k++) {
						if (hwList.get(j).getBrand().getBrand()
								.equals(getBrandById(list.get(k)).getBrand())) {
							matchList.add(hwList.get(j));
							break;
						}
					}
				}
			} else if (s.equals(Constant.mbItemNameList[1])) {
				List<Integer> list = map.get(s);

				for (int j = 0; j < hwList.size(); j++) {
					for (int k = 0; k < list.size(); k++) {
						if (Changer.checkPrice(hwList.get(j),
								Constant.MAINBOARD_PRICE[list.get(k) - 1]
										.getName())) {
							matchList.add(hwList.get(j));
							break;
						}
					}
				}

			} else if (s.equals(Constant.mbItemNameList[2])) {
				List<Integer> list = map.get(s);

				for (int j = 0; j < hwList.size(); j++) {
					for (int k = 0; k < list.size(); k++) {
						if (hwList.get(j).getMBArchitect().getValue()
								.equals(getValueByID(list.get(k)).getValue())) {
							matchList.add(hwList.get(j));
							break;
						}
					}
				}

			} else if (s.equals(Constant.mbItemNameList[3])) {
				List<Integer> list = map.get(s);

				for (int j = 0; j < hwList.size(); j++) {
					for (int k = 0; k < list.size(); k++) {
						if (hwList
								.get(j)
								.getCPUSlot()
								.getName()
								.equals(getInterfaceByID(list.get(k)).getName())) {
							matchList.add(hwList.get(j));
							break;
						}
					}
				}

			} else if (s.equals(Constant.mbItemNameList[4])) {
				List<Integer> list = map.get(s);

				for (int j = 0; j < hwList.size(); j++) {
					for (int k = 0; k < list.size(); k++) {
						if (hwList.get(j).getMaxMem().getValue()
								.equals(getValueByID(list.get(k)).getValue())) {
							matchList.add(hwList.get(j));
							break;
						}
					}
				}

			}
			if (i != keys.size()) {
				hwList = matchList;
				matchList = new ArrayList<MainBoard>();
			}
		}
		
		return matchList.size();

	}

	@Override
	public int getListPageNum(HardwareSet hs) {

		Session sess = sessionFactory.getCurrentSession();
		String sql = "FROM MainBoard WHERE STATE=882";
		List<MainBoard> list = sess.createQuery(sql).list();
		list = uniFilter(hs, list);
		return list.size();
	}

	private List<MainBoard> uniFilter(HardwareSet hs, List<MainBoard> list) {
		if (hs != null) {
			list = CPUFilter(hs, list);
			list = MemoryFilter(hs, list);
			list = GraphicsFilter(hs, list);
			list = DiskFilter(hs, list);
			list = ChassisFilter(hs, list);
		}
		return list;
	}

	@Override
	public List<MainBoard> getOneBySupplierID(int id) {
		// TODO Auto-generated method stub
		Session sess = sessionFactory.getCurrentSession();
		String sql = "FROM MainBoard where SUPPLIER="+id;
		List<MainBoard> list = sess.createQuery(sql).list();
		
		return list;
	}
}
